﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace intTrans
{
    class imageByteConverter
    {
        private int _imageHeight;
        private int _imageWidth;
        private PixelFormat _colorDepth;
        private int _stride;
        private int _bytesPerPixel;

        public byte[] ImageToByteArray(System.Drawing.Bitmap imageIn)
        {
            if (imageIn.PixelFormat == PixelFormat.Format24bppRgb || imageIn.PixelFormat == PixelFormat.Format32bppArgb)
            {

                BitmapData bmpData = imageIn.LockBits(new Rectangle(0, 0, imageIn.Width, imageIn.Height), ImageLockMode.ReadOnly, imageIn.PixelFormat);
                int pixelbytes = Bitmap.GetPixelFormatSize(imageIn.PixelFormat) / 8;
                IntPtr ptr = bmpData.Scan0;
                int size = Math.Abs(bmpData.Stride) * imageIn.Height;
                byte[] byteOut = new byte[size];

                System.Runtime.InteropServices.Marshal.Copy(ptr, byteOut, 0, size);

                imageIn.UnlockBits(bmpData);

                _imageWidth = imageIn.Width;
                _imageHeight = imageIn.Height;
                _colorDepth = imageIn.PixelFormat;
                _stride = bmpData.Stride;
                _bytesPerPixel = pixelbytes;
                return byteOut;
            }
            else throw new Exception("PixelFormat");
        }

        public Image ByteArrayToImage(byte[] byteArrayIn)
        {

            Bitmap picOut = new Bitmap(_imageWidth, _imageHeight, _colorDepth);

            BitmapData bmpData = picOut.LockBits(new Rectangle(0, 0, _imageWidth, _imageHeight), ImageLockMode.WriteOnly, _colorDepth);
            IntPtr ptr = bmpData.Scan0;
            int size = bmpData.Stride * _imageHeight;

            System.Runtime.InteropServices.Marshal.Copy(byteArrayIn, 0, ptr, size);
            picOut.UnlockBits(bmpData);
            return picOut;
        }

        public int imageHeight() { return _imageHeight; }
        public int imageWidth() { return _imageWidth; }
        public PixelFormat colorDepth() { return _colorDepth; }
        public int stride() { return _stride; }
        public int bytesPerPixel() { return _bytesPerPixel; }
    }
}
